<template>
	<view class="Chatmain" :style="{
			height: leftChatNav.length > 5 ? '100%' : '100vh'
		}">
		<!-- <scroll-view scroll-y="true" class="scroll-container" id="scrollView" :scroll-top="scrollTop" @scrolltoupper="loadHistory" upper-threshold="50"> -->
		<!-- 名字 -->
		<u-sticky offset-top="0">
			<view class="title">
				<!-- <u-icon class="titleicon" name="arrow-left" size="25" @click="backNews"></u-icon> -->
				<view class="titleinfo">{{ msgUserinfo.name }}</view>
			</view>
		</u-sticky>
		<!-- 聊天内容 -->
		<!-- 当前发送右边 -->
		<!-- leftChatNav -->
		<!-- v-if="userinfoList.id == item.user_id" -->
		<scroll-view :scroll-into-view="viewIndex" scroll-view scroll-with-animation="true" scroll-y="true"
			class="scroll-Y">
			<view class="ChatNav">
				<view v-for="(item, index) in leftChatNav" :key="index" @click="closeMore">
					<view class="rightChatNav" v-if="userinfoList.uid == item.user_id">
						<view class="chatAvatar"><u-avatar size="45" :src="userinfoList.avatar"></u-avatar></view>
						<view class="chatInfo">
							<!-- 文字 -->
							<view class="chaText" v-if="item.msg_type === 1">
								<view class="chatMessage">
									{{ item.content }}
								</view>
							</view>
							<!-- 图片 -->
							<view class="chatimg" v-if="item.msg_type == 2 && item.file.type == 1"
								@click="previewImg(item.file.file_url)">
								<u--image :showLoading="true" :src="item.file.file_url" :width="item.contentAndwh.w"
									:height="item.contentAndwh.h"></u--image>
							</view>
							<!-- 视频 -->
							<view class="chatVideo"
								v-if="item.msg_type == 2 && (item.file.type == 3 || item.file.type == 2)">
								<view class="downloadInco">
									<u-icon name="download" size="28" v-if="item.file.type == 3"
										@click="downloadFile(item)"></u-icon>
								</view>
								<video id="myVideo" :src="item.file.file_url" @error="videoErrorCallback"
									:poster="`${item.file.file_url}?x-oss-process=video/snapshot,t_${seek},f_jpg`"
									width="100" height="130"></video>
							</view>
							<!-- 文件 -->
							<view class="downloadF">
								<view class="downloadInco">
									<u-icon name="download" size="28" v-if="item.file.type == 4"
										@click="downloadFile(item)"></u-icon>
								</view>
								<view class="chatFile" v-if="item.msg_type == 2 && item.file.type == 4">
									<view class="chatFileInfo">
										<view class="name u-line-2">{{ item.file.original_name }}</view>
										<view class="size u-line-1">{{ item.file.size }}</view>
									</view>
									<view class="">
										<u-icon name="file-text-fill" size="50"></u-icon>
									</view>
								</view>
							</view>
							<view>
								<view class="chatTime">{{ item.created_at }}</view>
							</view>
						</view>
					</view>
					<!-- 接收左边 -->
					<!-- 右边 -->
					<!-- v-if="msgUserinfo.receiver_id == item.id" -->
					<view class="leftChatNav" v-if="msgUserinfo.receiver_id == item.user_id">
						<view class="chatAvatar"><u-avatar size="45" :src="msgUserinfo.avatar"></u-avatar></view>
						<view class="chatInfo">
							<!-- 文字 -->
							<view class="chaText" v-if="item.msg_type === 1">
								<view class="chatMessage">
									{{ item.content }}
								</view>
							</view>
							<!-- 图片 -->
							<view class="chatimg" v-if="item.msg_type === 2 && item.file.type == 1"
								@click="previewImg(item.file.file_url)">
								<u--image :showLoading="true" :src="item.file.file_url" :width="item.contentAndwh.w"
									:height="item.contentAndwh.h"></u--image>
							</view>
							<!-- 视频 -->
							<view class="chatVideo"
								v-if="item.msg_type == 2 && (item.file.type == 3 || item.file.type == 2)">
								<video id="myVideo" :src="item.file.file_url" @error="videoErrorCallback"
									:poster="`${item.file.file_url}?x-oss-process=video/snapshot,t_${seek},f_jpg`"
									width="100" height="130"></video>
								<view class="downloadInco">
									<u-icon name="download" size="28" v-if="item.file.type == 3"
										@click="downloadFile(item)"></u-icon>
								</view>
							</view>
							<!-- 文件 -->
							<view class="downloadF">
								<view class="downloadInco">
									<u-icon name="download" size="28" v-if="item.file.type == 4"
										@click="downloadFile(item)"></u-icon>
								</view>
								<view class="chatFile" v-if="item.msg_type == 2 && item.file.type == 4">
									<view class="chatFileInfo">
										<view class="name u-line-2">{{ item.file.original_name }}</view>
										<view class="size u-line-1">{{ item.file.size }}</view>
									</view>
									<view class="">
										<u-icon name="file-text-fill" size="50"></u-icon>
									</view>
								</view>
							</view>
							<view>
								<view class="chatTime">{{ item.created_at }}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 可滚动到底部的view标签 -->
			<view :id="'im_' + leftChatNav.length" class="bottom"></view>
		</scroll-view>
		<!-- </scroll-view> -->
		<!-- 输入框 -->
		<view class="textareaB">
			<view class="butIcon">
				<u--textarea maxlength="500" @confirm="onConfirm" v-model="value" placeholder="按Enter发送
			" autoHeight></u--textarea>
				<view class="emit">
					<u-icon class="circle" name="plus-circle" size="35" @click="moreFunction"></u-icon>
					<u-icon name="https://pic.imgdb.cn/item/668510e8d9c307b7e91175f3.png" size="35"
						@click="emitMssage"></u-icon>
				</view>
			</view>
			<!-- <view class="but"><u-button type="primary" text="发送"></u-button></view> -->
			<u-transition :show="show" mode="slide-up">
				<view v-if="isMoer" class="more">
					<view class="moreInfo">
						<view class="moreText" @click="chooseImage">
							<u-icon name="photo-fill" size="50"></u-icon>
							<view>照片</view>
						</view>
						<view class="moreText" @click="chooseVideo">
							<u-icon name="camera-fill" size="50"></u-icon>
							<view>视频</view>
						</view>
						<view class="moreText" @click="chooseFile">
							<u-icon name="file-text-fill" size="50"></u-icon>
							<view>文件</view>
						</view>
					</view>
				</view>
			</u-transition>
		</view>
		<view :style="{
				height: isMoer ? '550rpx' : '150rpx'
			}"></view>
	</view>
</template>

<script>
	import {
		imTalkRecords,
		imUsersSetting,
		imMessageText,
		imMessageImage,
		imMultipartInitiate,
		imMessageFile
	} from '../../../api/imInterface.js'
	// import { userinfo } from '../../../api/Mine.js'
	import websocetObj from '@/util/webSocket.js'
	// import ss_download from '@/uni_modules/ss-download/components/ss-download/ss-download.vue';
	export default {
		data() {
			return {
				seek: 2,
				msgUserinfo: [],
				leftChatNav: [],
				// 当前登录的
				userinfoList: [],
				value: '',
				Time: '',
				isMoer: false,
				show: false,
				scrollTop: 0, // 初始滚动位置
				fileUrl: '',
				fileType: '',
				viewIndex: ''
			}
		},
		onShow() {
			setTimeout(() => {
				document.body.scrollTop = document.documentElement.scrollTop = 9999999
			}, 20)
		},
		onLoad(option) {
			const {
				params
			} = option
			// console.log(params)
			this.msgUserinfo = JSON.parse(params)
			// if (this.msgUserinfo.receiver_id) {
			// 	this.msgUserinfo.id = this.msgUserinfo.receiver_id;
			// }
			console.log(this.msgUserinfo, '老师')
			this.getimTalkRecords()
			this.getUserinfoList()
			this.emitMsg()
			// this.getSocket()
			const date = new Date()
			const year = date.getFullYear()
			const month = date.getMonth() + 1 //注意月份从0开始，所以要加1
			const day = date.getDate()
			const hour = date.getHours()
			const minute = date.getMinutes()
			const formattedMonth = month < 10 ? `0${month}` : month // 如果月份小于10，前面加0
			const formattedDay = day < 10 ? `0${day}` : day // 如果日期小于10，前面加0
			const formattedHour = hour < 10 ? `0${hour}` : hour // 如果小时小于10，前面加0
			const formattedMinute = minute < 10 ? `0${minute}` : minute // 如果分钟小于10，前面加0
			const dateTime = `${formattedMonth}-${formattedDay} ${formattedHour}:${formattedMinute}`
			// this.Time = ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
			this.Time = dateTime
			//请求连接
			websocetObj.createSocket()
		},
		onUnload() {
			console.log('页面卸载')
			// 关闭连接
			websocetObj.closeSocket()
		},
		methods: {
			videoErrorCallback(e) {
				console.log(e)
			},
			// 获取聊天记录
			async getimTalkRecords() {
				let res = await imTalkRecords({
					talk_type: 1,
					receiver_id: this.msgUserinfo.receiver_id,
					limit: 30,
					record_id: 0
				})
				// console.log(res)
				if (res.code === 200) {
					// 处理图片大小
					res.data.rows.forEach(item => {
						item.contentAndwh = {
							w: 0,
							h: 0
						}
						if (item.msg_type == 2) {
							uni.getImageInfo({
								src: item.file.file_url,
								success: res => {
									item.contentAndwh.w = res.width
									item.contentAndwh.h = res.height
									item.contentAndwh = this.setPicSize(item.contentAndwh)
								}
							})
						}
						this.leftChatNav.push({
							...item
						})
						// console.log(item)
					})
					console.log(this.leftChatNav, '当前聊天记录')
					// 滚动到底部
					this.$nextTick(function() {
						setTimeout(() => {
							document.body.scrollTop = document.documentElement.scrollTop = 9999999
						}, 100)
					})
				} else {
					uni.showToast({
						title: '获取失败',
						icon: 'error'
					})
				}
			},
			// 获取当前用户个人信息
			async getUserinfoList() {
				let {
					data,
					code
				} = await imUsersSetting()
				// console.log(data)
				// console.log(code)
				if (code === 200) {
					this.userinfoList = data.user_info

					// console.log(this.userinfoList, '用户')
				} else {
					uni.showToast({
						title: '获取失败',
						icon: 'error'
					})
				}
			},
			// 发送消息
			async emitMssage() {
				if (this.value !== '') {
					// let datares = {
					// 	user_id: this.userinfoList.uid,
					// 	content: this.value,
					// 	created_at: this.Time
					// }
					let newData = {
						talk_type: 1,
						receiver_id: this.msgUserinfo.receiver_id,
						text: this.value
					}
					// this.leftChatNav.push(datares)
					// 使用封装方法发送
					// websocetObj.sendMsg(newData)
					// this.emitMsg()
					// document.body.scrollTop = document.documentElement.scrollTop = 9999999
					let res = await imMessageText(newData)
					if (res.code != 200) {
						uni.showToast({
							title: '发送失败',
							icon: 'error'
						})
					}
					this.value = ''
					console.log(res)
				}
			},
			// 接受
			// emitMsg() {
			// 	uni.$on('message', val => {
			// 		if (val.event === 'event_talk') {
			// 			document.body.scrollTop = document.documentElement.scrollTop = 9999999
			// 			this.leftChatNav.push(val.content.data)
			// 		}
			// 	})
			// },
			emitMsg() {
				uni.$on('message', val => {
					if (val.event === 'event_talk') {
						document.body.scrollTop = document.documentElement.scrollTop = 9999999
						val.content.data.contentAndwh = {
							w: 0,
							h: 0
						}
						if (val.content.data.msg_type == 2) {
							uni.getImageInfo({
								src: val.content.data.file.file_url,
								success: res => {
									val.content.data.contentAndwh.w = res.width
									val.content.data.contentAndwh.h = res.height
									val.content.data.contentAndwh = this.setPicSize(val.content.data
										.contentAndwh)
								}
							})
						}
						// this.leftChatNav.push(val.content.data)

						const isDuplicate = this.leftChatNav.some(item => item.id === val.content.data.id)
						if (!isDuplicate) {
							this.leftChatNav.push(val.content.data)
						}
						
						this.$nextTick(() => {
							uni.pageScrollTo({
								scrollTop: 10000, // 假设一个大数值，滚动到页面底部
								duration: 0
							});
							this.viewIndex = 'im_' + this.leftChatNav.length;
							document.body.scrollTop = document.documentElement.scrollTop = 9999;
						});
					}
				})
			},
			// 更多功能 发图片 发文件
			moreFunction() {
				document.body.scrollTop = document.documentElement.scrollTop = 9999999
				// console.log(123);
				this.isMoer = !this.isMoer
				this.show = !this.show
			},
			// 关闭更多功能
			closeMore() {
				this.isMoer = false
				this.show = false
			},
			// 发送图片
			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: res => {
						const imfFile = res.tempFilePaths
						uni.showLoading({
							title: '加载中'
						})
						console.log(imfFile)
						uni.uploadFile({
							url: 'https://imcnpe.knew-how.com/api/v1/talk/message/image', //仅为示例，非真实的接口地址
							header: {
								Authorization: uni.getStorageSync('access_token')
							},
							filePath: imfFile[0],
							formData: {
								talk_type: 1,
								receiver_id: this.msgUserinfo.receiver_id
							},
							name: 'image',
							success: res => {
								console.log(res)
								document.body.scrollTop = document.documentElement.scrollTop =
									9999999
								this.isMoer = false
								this.show = false
								uni.hideLoading()
							}
						})
					}
				})
			},
			// 预览图片
			previewImg(item) {
				let arr = []
				arr.push(item)
				// 预览图片
				uni.previewImage({
					urls: arr,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片')
						},
						fail: function(err) {
							console.log(err.errMsg)
						}
					}
				})
			},
			// 下载视频和文件
			downloadFile(item) {
				// console.log(item.file.original_name)
				// console.log(item.file.file_url)
				uni.getSystemInfo({
					success: function(res) {
						if (res.platform === 'ios') {
							console.log('当前设备是 ios')
							// // 创建一个隐藏的链接元素
							const link = document.createElement('a')
							link.href = item.file.file_url
							// 指定下载的文件名
							link.download = item.file.original_name || 'downloadedFile'
							// 将链接元素添加到 DOM
							document.body.appendChild(link)
							// 模拟点击链接以触发下载
							link.click()
							// 下载完成后移除链接元素
							document.body.removeChild(link)
						} else if (res.platform === 'android') {
							console.log('当前设备是 Android')
							uni.setClipboardData({
								data: item.file.file_url,
								success: function(res) {
									console.log(res)
									uni.showToast({
										title: '复制下载地址成功，请打开浏览器粘贴地址下载',
										icon: 'none',
										duration: 3500
									})
								},
								fail: function(err) {
									uni.showToast({
										title: '复制失败',
										icon: 'none',
										duration: 2000
									})
									console.error('复制失败: ', err)
								}
							})
						} else {
							console.log('当前设备是其他平台')
						}
					},
					fail: function(err) {
						console.error('获取系统信息失败: ', err)
					}
				})
			},
			// 发送文件
			async imMessageFile(upload_id) {
				let {
					data,
					code
				} = await imMessageFile({
					talk_type: 1,
					receiver_id: this.msgUserinfo.receiver_id,
					upload_id: upload_id
				})
				// console.log(data)
				// console.log(code)
				if (code === 200) {
					//this.getimTalkRecords()
					document.body.scrollTop = document.documentElement.scrollTop = 9999999
				} else {
					uni.showToast({
						title: '获取失败',
						icon: 'error'
					})
				}
			},

			// 选择文件
			chooseFile() {
				let that = this
				uni.chooseFile({
					count: 1, //默认100
					type: 'all',
					success: async res => {
						let data = await imMultipartInitiate({
							file_name: res.tempFiles[0].name,
							file_size: res.tempFiles[0].size
						})
						uni.showLoading({
							title: '加载中'
						})
						console.log(data)
						const File = res.tempFilePaths
						console.log(File, 'FileFileFile')
						if (data.code === 200) {
							uni.uploadFile({
								url: 'https://imcnpe.knew-how.com/api/v1/upload/multipart', //仅为示例，非真实的接口地址
								header: {
									Authorization: uni.getStorageSync('access_token')
								},
								filePath: File[0],
								formData: {
									upload_id: data.data.upload_id,
									split_index: 0,
									split_num: 1
								},
								name: 'file',
								success: res => {
									if (res.data) {
										let data = JSON.parse(res.data)
										that.imMessageFile(data.data.upload_id)
										console.log(data.data.upload_id)
										uni.hideLoading()
									}
									this.isMoer = false
									this.show = false
								}
							})
						}
					}
				})
			},
			// 选择视频
			chooseVideo() {
				let that = this
				uni.chooseVideo({
					sourceType: ['camera', 'album'],
					success: async res => {
						let data = await imMultipartInitiate({
							file_name: res.name,
							file_size: res.size
						})
						uni.showLoading({
							title: '加载中'
						})
						const File = res.tempFilePath
						console.log(res)
						console.log(File, 'FileFileFile')
						if (data.code === 200) {
							uni.uploadFile({
								url: 'https://imcnpe.knew-how.com/api/v1/upload/multipart', //仅为示例，非真实的接口地址
								header: {
									Authorization: uni.getStorageSync('access_token')
								},
								filePath: File,
								formData: {
									upload_id: data.data.upload_id,
									split_index: 0,
									split_num: 1
								},
								name: 'file',
								success: res => {
									console.log(res)
									if (res.data) {
										let data = JSON.parse(res.data)
										that.imMessageFile(data.data.upload_id)
										console.log(data.data.upload_id)
										uni.hideLoading()
									}
									this.isMoer = false
									this.show = false
								}
							})
						}
					}
				})
			},

			//处理图片
			setPicSize(content) {
				// console.log(content)
				// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
				let maxW = uni.upx2px(350) //350是定义消息图片最大宽度
				let maxH = uni.upx2px(350) //350是定义消息图片最大高度
				if (content.w > maxW || content.h > maxH) {
					let scale = content.w / content.h
					content.w = scale > 1 ? maxW : maxH * scale
					content.h = scale > 1 ? maxW / scale : maxH
				}
				// console.log(content, 'bggg')
				return content
			}
		}
	}
</script>

<style lang="scss" scoped>
	button::after {
		border: none;
	}

	.ChatNav {
		// margin-bottom: -30rpx;
	}

	/deep/ .u-sticky {
		top: 0 !important;
	}

	.Chatmain {
		// background: #eef0f3;
		height: 100%;

		// overflow-x: auto;
		.title {
			border-bottom: 1px solid #ececec;
			align-items: center;
			display: flex;
			width: 750rpx;
			height: 75rpx;
			// font-weight: 600;
			font-family: 'Microsoft Yahei';
			// font-size: 30rpx;
			background: #ebeef1;

			.titleinfo {
				flex: 1;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #000000;
			}
		}
	}

	#myVideo {
		width: 400rpx;
		height: 250rpx;
		border-radius: 16rpx;
		// z-index: 1;
	}

	//左边每一条聊天
	.leftChatNav {
		display: flex;
		align-items: flex-start;
		margin: 30rpx 80rpx 10rpx 20rpx;

		.chatInfo {
			margin: 15rpx 0 0 15rpx;

			.chaText {
				display: flex;
				align-items: center;
				/* justify-content: flex-start; */
				flex-direction: row;
			}

			.chatMessage {
				border-bottom-left-radius: 15rpx;
				border-bottom-right-radius: 15rpx;
				border-top-right-radius: 15rpx;
				padding: 15rpx 20rpx;
				max-width: 550rpx;
				font-size: 26rpx;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				background: #f5f6f8;
				// height: 100%;
			}

			.chatTime {
				margin-top: 10rpx;
				font-size: 24rpx;
				color: #cacaca;
			}

			.utag {
				color: #969696;
				font-size: 20rpx;
			}

			.downloadF {
				display: flex;
				align-items: center;
				background: #eef0f3;

				.downloadInco {
					margin-right: 15rpx;
				}
			}
		}

		.chatFile {
			width: 300rpx;
			display: flex;
			background: #eef0f3;
			justify-content: space-between;
			padding: 10rpx 20rpx;
			border-radius: 10rpx;

			.size {
				font-size: 25rpx;
				color: #969696;
				margin-top: 20rpx;
			}

			.name {
				width: 200rpx;
			}
		}

		.chatVideo {
			display: flex;
			align-items: center;

			.downloadInco {
				margin-left: 15rpx;
			}
		}
	}

	// 右边每一条聊天记录
	.rightChatNav {
		display: flex;
		align-items: flex-start;
		flex-direction: row-reverse;
		margin: 30rpx 20rpx 10rpx 80rpx;

		.chatInfo {
			margin: 15rpx 15rpx 0 0;

			.chaText {
				display: flex;
				align-items: center;
				/* justify-content: flex-start; */
				flex-direction: row-reverse;
			}

			.chatMessage {
				border-bottom-left-radius: 15rpx;
				border-bottom-right-radius: 15rpx;
				border-top-left-radius: 15rpx;
				padding: 15rpx 20rpx;
				max-width: 550rpx;
				word-wrap: break-word;
				/* 自动换行 */
				font-size: 26rpx;
				display: inline-block;
				background: #fc761e;
				// height: 100%;
				// display: flex;
				color: #ffffff;
			}

			.chatTime {
				text-align: right;
				margin-top: 10rpx;
				font-size: 24rpx;
				color: #cacaca;
			}

			.chatFile {
				width: 300rpx;
				display: flex;
				background: #eef0f3;
				justify-content: space-between;
				padding: 10rpx 20rpx;
				border-radius: 10rpx;

				.size {
					font-size: 25rpx;
					color: #969696;
					margin-top: 20rpx;
				}

				.name {
					width: 200rpx;
				}
			}

			.downloadF {
				display: flex;
				align-items: center;

				.downloadInco {
					margin-right: 15rpx;
				}
			}
		}

		// .unittt {
		// 	display: flex;
		// 	align-items: center;
		// 	justify-content: space-between;
		// }
		.utag {
			margin-top: 15rpx;
			color: #969696;
			font-size: 22rpx;
		}

		.chatVideo {
			display: flex;
			align-items: center;

			.downloadInco {
				margin-right: 15rpx;
			}
		}
	}

	// 输入框
	.textareaB {
		display: flex;
		align-items: center;
		flex-direction: column;
		padding: 15rpx;
		position: fixed;
		// top: 0;
		bottom: 0;
		background: #ffffff;
		left: 0;
		right: 0;
		z-index: 9999;

		.emit {
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 0 20rpx;

			.circle {
				margin-right: 30rpx;
			}
		}

		.but {
			padding: 10rpx 0 0 15rpx;
			width: 110rpx;
		}

		.butIcon {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.more {
			margin-top: 15rpx;
			width: 750rpx;
			border-top: 1px solid #ebeef1;
			height: 400rpx;
			background: #ffffff;

			.moreInfo {
				margin-top: 20rpx;
				display: flex;
				// align-items: center;
				// justify-content: space-around;
				flex-wrap: wrap;
				justify-content: flex-start;

				/* 确保项目靠左对齐 */
				.moreText {
					flex: 1 0 25%;
					/* 让每个项目占用25%的宽度 */
					max-width: 20%;
					/* 确保每个项目的最大宽度为25% */
					margin: 20rpx 0;
					display: flex;
					justify-content: center;
					align-items: center;
					flex-direction: column;
				}
			}
		}
	}

	// .scroll-container {
	// 	height: 100%;
	// }
	/deep/ .u-textarea--radius {
		border-radius: 50rpx;
	}
</style>